<template>
  <div class="violations-container">
	<el-row type="flex" justify="center" class="page-header" style="margin-bottom: 30px;">
	        <el-col :span="24" class="text-center">
	            <div class="title-wrapper">
	            <i class="el-icon-search el-icon--large"></i>
	            <h1 class="main-title">垃圾违规信息管理系统</h1>
	            <p class="sub-title">严管每一条垃圾违规记录，细查每一次不规范行为，用精准管理守护环境整洁，让文明投放成为日常</p>
	            </div>
	        </el-col>
	    </el-row>
    <!-- 详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="违规记录详情"
      width="70%"
      destroy-on-close
    >
      <el-descriptions title="违规记录信息" direction="vertical" :column="4" :model="currentViolation" border>
        <el-descriptions-item label="记录ID" :span="2">{{ currentViolation.violationId }}</el-descriptions-item>
        <el-descriptions-item label="垃圾桶ID" :span="2">{{ currentViolation.binId }}</el-descriptions-item>
        <el-descriptions-item label="违规者ID" :span="2">{{ currentViolation.violatorId }}</el-descriptions-item>
        <el-descriptions-item label="违规类型" :span="2">{{ currentViolation.violationType }}</el-descriptions-item>
        <el-descriptions-item label="违规时间" :span="4">{{ formatDateTime(currentViolation.violationDate) }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>


    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑违规记录"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="editForm" 
        :rules="rules" 
        ref="editFormRef" 
        label-width="120px" 
        class="demo-ruleForm"
      >
        <el-form-item label="记录ID" prop="violationId" disabled>
          <el-input v-model="editForm.violationId"></el-input>
        </el-form-item>
        <el-form-item label="垃圾桶ID" prop="binId">
          <el-input v-model="editForm.binId"></el-input>
        </el-form-item>
        <el-form-item label="违规者ID" prop="violatorId">
          <el-input v-model.number="editForm.violatorId" type="number"></el-input>
        </el-form-item>
        <el-form-item label="违规类型" prop="violationType">
          <el-select v-model="editForm.violationType" placeholder="请选择违规类型">
            <el-option label="不当丢弃" value="Improper Disposal"></el-option>
            <el-option label="损坏" value="Damage"></el-option>
            <el-option label="其他" value="Other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
          <el-button @click="editDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增违规记录"
      width="60%"
      destroy-on-close
    >
      <el-form 
        :model="addForm" 
        :rules="rules" 
        ref="addFormRef" 
        label-width="120px"
      >
        <el-form-item label="垃圾桶ID" prop="binId">
          <el-input v-model="addForm.binId" placeholder="例如: LJ000001"></el-input>
        </el-form-item>
        <el-form-item label="违规者ID" prop="violatorId">
          <el-input v-model.number="addForm.violatorId" type="number" placeholder="请输入违规者ID"></el-input>
        </el-form-item>
        <el-form-item label="违规类型" prop="violationType">
          <el-select v-model="addForm.violationType" placeholder="请选择违规类型">
            <el-option label="不当丢弃" value="Improper Disposal"></el-option>
            <el-option label="损坏" value="Damage"></el-option>
            <el-option label="其他" value="Other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddForm">提交</el-button>
          <el-button @click="addDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <!-- 数据操作区和表格部分与之前相同 -->
    <el-row>
      <el-row :gutter="10" style="width: 100%; margin-bottom: 20px; align-items: center;">
        <el-col :span="6">
          <el-input 
            placeholder="输入垃圾桶ID进行查询" 
            v-model="searchBinId" 
            style="width: 100%;"
            @keyup.enter="handleSearch"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-select 
            v-model="searchViolationType" 
            placeholder="按违规类型筛选" 
            style="width: 100%;"
          >
            <el-option label="全部类型" value=""></el-option>
            <el-option label="不当丢弃" value="Improper Disposal"></el-option>
            <el-option label="损坏" value="Damage"></el-option>
            <el-option label="其他" value="Other"></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="handleSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-search"></i> 搜索
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="success" 
            @click="resetSearch" 
            style="width: 100%;"
          >
            <i class="el-icon-refresh"></i> 重置
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button 
            type="primary" 
            @click="openAddDialog" 
            style="width: 100%;"
          >
            <i class="el-icon-plus"></i> 新增
          </el-button>
        </el-col>
      </el-row>
      
      <!-- 表格部分 -->
      <el-table 
        :data="filteredData.slice((currentPage-1)*pageSize, currentPage*pageSize)" 
        border 
        style="width: 100%;"
        height="450"
      >
        <el-table-column prop="violationId" label="记录ID" width="100" align="center"></el-table-column>
        <el-table-column prop="binId" label="垃圾桶ID" width="120" align="center"></el-table-column>
        <el-table-column prop="violatorId" label="违规者ID" width="120" align="center"></el-table-column>
        <el-table-column prop="violationType" label="违规类型" width="140" align="center">
          <template #default="scope">
            <el-tag :type="getViolationTypeTag(scope.row.violationType)">
              {{ getViolationTypeName(scope.row.violationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="violationDate" label="违规时间" width="180" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.violationDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button type="primary" size="mini" @click="openDetailDialog(scope.row)">
                <i class="el-icon-view"></i> 查看
              </el-button>
              <el-button type="warning" size="mini" @click="openEditDialog(scope.row)">
                <i class="el-icon-edit"></i> 编辑
              </el-button>
              <el-button type="danger" size="mini" @click="deleteViolation(scope.row)">
                <i class="el-icon-delete"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-row type="flex" justify="center" style="margin-top: 20px;">
        <el-pagination 
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5,10,20,50]" 
          :page-size="pageSize" 
          :total="filteredData.length"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-row>
    </el-row>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import { post } from '../../utils/axios.js'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'


// 对话框状态
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const addDialogVisible = ref(false)


// 搜索条件
const searchBinId = ref('')
const searchViolationType = ref('')


// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)


// 数据存储
const violationsList = ref([])
const filteredData = ref([])


// 表单引用
const editFormRef = ref(null)
const addFormRef = ref(null)


// 当前选中的违规记录信息
const currentViolation = reactive({
  violationId: null,
  binId: '',
  violatorId: null,
  violationType: '',
  violationDate: null
})


// 编辑表单数据
const editForm = reactive({
  violationId: null,
  binId: '',
  violatorId: null,
  violationType: ''
})


// 新增表单数据
const addForm = reactive({
  binId: '',
  violatorId: null,
  violationType: ''
})


// 表单验证规则 - 修改了violatorId的验证规则
const rules = reactive({
  binId: [
    { required: true, message: '请输入垃圾桶ID', trigger: 'blur' }
  ],
  violatorId: [
    { required: true, message: '请输入违规者ID', trigger: 'blur' },
    { type: 'number', message: '违规者ID必须为数字', trigger: 'blur' }
    // 移除了8位数字的限制验证
  ],
  violationType: [
    { required: true, message: '请选择违规类型', trigger: 'change' }
  ]
})


// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '无记录'
  // 处理字符串格式的日期时间
  if (typeof dateTime === 'string') {
    // 尝试解析不同格式的日期字符串
    const date = new Date(dateTime)
    if (!isNaN(date.getTime())) {
      return date.toLocaleString()
    }
    return dateTime
  }
  // 处理Date对象
  return dateTime.toLocaleString()
}


// 根据违规类型获取显示名称
const getViolationTypeName = (type) => {
  switch(type) {
    case 'Improper Disposal': return '不当丢弃'
    case 'Damage': return '损坏'
    case 'Other': return '其他'
    default: return type
  }
}


// 根据违规类型获取标签样式
const getViolationTypeTag = (type) => {
  switch(type) {
    case 'Improper Disposal': return 'warning'
    case 'Damage': return 'danger'
    case 'Other': return 'info'
    default: return ''
  }
}


// 打开详情对话框
function openDetailDialog(row) {
  dialogVisible.value = true
  Object.assign(currentViolation, row)
}


// 打开编辑对话框
function openEditDialog(row) {
  editDialogVisible.value = true
  Object.assign(editForm, {
    violationId: row.violationId,
    binId: row.binId,
    violatorId: row.violatorId,
    violationType: row.violationType
  })
}


// 打开新增对话框
function openAddDialog() {
  addDialogVisible.value = true
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  addForm.binId = ''
  addForm.violatorId = null
  addForm.violationType = ''
}


// 提交编辑表单
function submitEditForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '更新中...' })
    post('/sc/trashbin-violations/updateById', editForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('更新成功！')
        editDialogVisible.value = false
        fetchViolationsList()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    })
  })
}


// 提交新增表单
function submitAddForm() {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    
    const loading = ElLoading.service({ text: '添加中...' })
    post('/sc/trashbin-violations/add', addForm, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('添加成功！')
        addDialogVisible.value = false
        fetchViolationsList()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    })
  })
}


// 删除违规记录
function deleteViolation(row) {
  ElMessageBox.confirm(`确定删除违规记录 ${row.violationId} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({ text: '删除中...' })
    post('/sc/trashbin-violations/deleteById', { violationId: row.violationId }, (res) => {
      loading.close()
      if (res.status === 1 || res.includes('成功')) {
        ElMessage.success('删除成功！')
        fetchViolationsList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    })
  }).catch(() => {})
}


// 搜索处理
function handleSearch() {
  const loading = ElLoading.service({ text: '搜索中...' })
  
  if (searchViolationType.value) {
    // 按违规类型搜索，调用后端接口
    post('/sc/trashbin-violations/byType', { violationType: searchViolationType.value }, (res) => {
      loading.close()
      if (res && res.data) {
        filteredData.value = res.data
      } else if (Array.isArray(res)) {
        filteredData.value = res
      } else {
        filteredData.value = []
      }
      
      showSearchResultMessage()
    })
  } else if (searchBinId.value) {
    // 按垃圾桶ID搜索，本地过滤
    filteredData.value = violationsList.value.filter(item => 
      item.binId.includes(searchBinId.value)
    )
    loading.close()
    showSearchResultMessage()
  } else {
    // 显示全部
    filteredData.value = [...violationsList.value]
    loading.close()
    showSearchResultMessage()
  }
  
  currentPage.value = 1 // 重置到第一页
}


// 显示搜索结果消息
function showSearchResultMessage() {
  if (filteredData.value.length > 0) {
    ElMessage.success(`找到 ${filteredData.value.length} 条记录`)
  } else {
    ElMessage.warning('未找到匹配记录')
  }
}


// 重置搜索
function resetSearch() {
  searchBinId.value = ''
  searchViolationType.value = ''
  filteredData.value = [...violationsList.value]
  currentPage.value = 1
}


// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val
  currentPage.value = 1
}


// 当前页变化
function handleCurrentChange(val) {
  currentPage.value = val
}



// 获取所有违规记录
function fetchViolationsList() {
  const loading = ElLoading.service({ text: '加载中...' })
  post('/sc/trashbin-violations/getAll', {}, (res) => {
    loading.close()
    if (res.status === 1 && res.data) {
      violationsList.value = res.data
      filteredData.value = [...res.data]
    } else {
      ElMessage.error(res.msg || '获取数据失败')
      violationsList.value = []
      filteredData.value = []
    }
  })
}


// 页面加载时获取数据
onMounted(() => {
  fetchViolationsList()
})
</script>


<style scoped>
.violations-container {
  width: auto;
  padding: 20px;
}
/* 标题样式 */
.page-header {
  padding: 10px 0;
  border-bottom: 1px solid #e5e7eb;
}

.title-wrapper {
  display: inline-flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 8px;
}

.main-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.sub-title {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.el-icon--large {
  font-size: 28px;
  color: #409eff;
}

.operation-buttons {
  display: flex;
  gap: 4px;
}


.operation-buttons .el-button--mini {
  padding: 1px 6px;
  font-size: 12px;
  height: 24px;
  min-width: auto;
}


.el-table {
  margin-top: 20px;
}


.el-pagination {
  margin-top: 20px;
}


.el-form-item .el-button,
.el-col .el-button {
  margin-right: 5px;
}


.el-form {
  padding: 10px;
}
</style>
    